<template>
  <div id="main">
    <Header />
    <Nav active="4" />
    <div class="example">
      <img src="@/assets/images/image_4.png">
      <div class="example-top">
        <el-form @submit.native.prevent label-width="auto">
          <div class="market_request">
            <div class="market_request_left">
              <el-form-item label="所属行业">
                <JnpfCascader v-model="query.industry" placeholder="请选择所属行业"
                  :options="industryOptions" :props="industryProps" clearable />
              </el-form-item>
              <el-form-item label="所属区域">
                <JnpfSelect v-model="query.region" placeholder="请选择所属区域" clearable
                  :options="regionOptions" :props="regionProps" multiple>
                </JnpfSelect>
              </el-form-item>
              <el-form-item label="改造后等级">
                <JnpfSelect v-model="query.levelafter" placeholder="请选择改造后等级" clearable
                  :options="levelafterOptions" :props="levelafterProps" multiple>
                </JnpfSelect>
              </el-form-item>
              <el-form-item label="所属区域">
                <JnpfSelect v-model="query.region" placeholder="请选择所属区域" clearable
                  :options="regionOptions" :props="regionProps" multiple>
                </JnpfSelect>
              </el-form-item>
            </div>
            <div style="display: flex;padding-right: 10px;">
              <el-button type="primary" @click="search()">查询</el-button>
              <el-button @click="reset()">重置</el-button>
            </div>
          </div>
        </el-form>
      </div>
      <div class="example-center">
        <el-empty v-if="total === 0" description="暂无数据"></el-empty>
        <div v-else v-for="item in list" :key="item.id" class="example-main">
          <a @click="goDetail(item.id)" class="example-list">
            <div class="example-left">
              <img v-if="!item.pic" src="@/assets/images/example.png" />
              <!--              部署的话改成'/cloud-api'-->
              <img v-if="item.pic" :src="'/cloud-api'+ item.pic[0].url" />
              <div class="image_shadow" v-if="item.clickNum">
                点击量：{{ item.clickNum }}
              </div>
            </div>
            <div class="example-right">
              <div class="example-name">{{ item.companyname }}</div>
              <div class="example-com">项目名称：{{ item.projectname }}</div>
              <div class="example-com">所属行业：{{  item.industry.split("/")[1] }}</div>
              <div class="example-com">所属区域：{{  item.region }}</div>
              <div class="example-com">合作服务商：{{ item.cooperationdigitalserver }}</div>
            </div>
            <div class="example_level_box">
              <div class="box_title">数字化水平等级</div>
              <div class="box_tags">
                <div style="text-align: center;">
                  <span>改造前</span>
                  <div class="tags">
                    <div class="tag gray">
                      {{ item.levelbefore }}
                    </div>
                  </div>
                </div>
                <div style="text-align: center;">
                  <span>改造后</span>
                  <div class="tags">
                    <div class="tag blue">
                      (预期){{ item.levelafter }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="box_info">查看详情</div>
            </div>
          </a>
        </div>
        <div class="general_pagination">
          <span class="total">{{ `共 ${total} 项数据` }}</span>
          <pagination layout="sizes, prev, pager, next, jumper" :total="total"
            :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
            @pagination="initData" :pageSizes="[5]" />
        </div>
        <Detail v-if="detailVisible" ref="Detail" @refresh="refresh" />
      </div>
    </div>
    <Link />
    <Floor />
  </div>
</template>

<script>

import request from '@/utils/request'
import { mapGetters } from "vuex";
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import JNPFForm from './form'
import Detail from './Detail'
import ExportBox from '@/components/ExportBox'
import ToFormDetail from '@/views/basic/dynamicModel/list/detail'
import { getDataInterfaceRes } from '@/api/systemData/dataInterface'
import { getConfigData } from '@/api/onlineDev/visualDev'
import { getDefaultCurrentValueUserIdAsync } from '@/api/permission/user'
import { getDefaultCurrentValueDepartmentIdAsync } from '@/api/permission/organize'
import columnList from './columnList'
import { thousandsFormat } from "@/components/Generator/utils/index"
import SuperQuery from '@/components/SuperQuery'
import superQueryJson from './superQueryJson'
import axios from "axios";
import Floor from '@/views/login/component/Floor'
import Link from '@/views/login/component/Link'
import Header from '@/views/login/component/Header'
import Nav from '@/views/login/component/Nav'

export default {
  components: {
    JNPFForm,
    Detail,
    ExportBox, ToFormDetail, SuperQuery,
    Floor,
    Link,
    Header,
    Nav
  },
  data() {
    return {
      activeIndex: '4',
      keyword: '',
      expandsTree: true,
      refreshTree: true,
      toFormDetailVisible: false,
      expandObj: {},
      columnOptions: [],
      mergeList: [],
      exportList: [],
      columnList,
      showAll: false,
      superQueryVisible: false,
      superQueryJson,
      uploadBoxVisible: false,
      detailVisible: false,
      query: {
        companyname: undefined,
        levelbefore: undefined,
        projectname: undefined,
        levelafter: undefined,
        enterprisenmae: undefined,
        cooperationdigitalserver: undefined,
        industry: undefined,
        region: undefined,
      },
      treeProps: {
        children: 'children',
        label: 'fullName',
        value: 'id',
        isLeaf: 'isLeaf'
      },
      list: [],
      listLoading: true,
      total: 0,
      queryData: {},
      listQuery: {
        superQueryJson: '',
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatortime",
      },
      formVisible: false,
      flowVisible: false,
      flowListVisible: false,
      flowList: [],
      exportBoxVisible: false,
      regionOptions: [],
      regionProps: { "label": "fullName", "value": "id" },
      industryOptions: [],
      industryProps: { "label": "fullName", "value": "id", "children": "children" },
      levelbeforeOptions: [{ "fullName": "无等级", "id": "0" }, { "fullName": "一级", "id": "1" }, {
        "fullName": "二级",
        "id": "2"
      }, { "fullName": "三级", "id": "3" }, { "fullName": "四级", "id": "4" }, { "fullName": "五级", "id": "5" }],
      levelbeforeProps: { "label": "fullName", "value": "id" },
      levelafterOptions: [{ "fullName": "无等级", "id": "0" }, { "fullName": "一级", "id": "1" }, {
        "fullName": "二级",
        "id": "2"
      }, { "fullName": "三级", "id": "3" }, { "fullName": "四级", "id": "4" }, { "fullName": "五级", "id": "5" }],
      levelafterProps: { "label": "fullName", "value": "id" },
      interfaceRes: {},
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    menuId() {
      return this.$route.meta.modelId || ''
    }
  },
  created() {
    this.getColumnList(),
      this.initSearchDataAndListData()
    this.getindustryOptions();
    this.getregionOptions();
    this.queryData = JSON.parse(JSON.stringify(this.query))
  },
  methods: {
    handleSelect(key, keyPath) {
    },
    redirectTologin() {
      this.$router.push({ path: '/login', query: { redirect: '/' } });
    },
    redirectToblogin() {
      const token = localStorage.getItem('jnpf_token');
      if (token) {
        this.$router.push("/home");
      } else {
        window.open("/blogin");
      }
    },
    goTo(path) {
      this.$router.push(path);
    },
    toDetail(defaultValue, modelId) {
      if (!defaultValue) return
      getConfigData(modelId).then(res => {
        if (!res.data || !res.data.formData) return
        let formData = JSON.parse(res.data.formData)
        formData.popupType = 'general'
        this.toFormDetailVisible = true
        this.$nextTick(() => {
          this.$refs.toFormDetail.init(formData, modelId, defaultValue)
        })
      })
    },
    toggleTreeExpand(expands) {
      this.refreshTree = false
      this.expandsTree = expands
      this.$nextTick(() => {
        this.refreshTree = true
        this.$nextTick(() => {
          this.$refs.treeBox.setCurrentKey(null)
        })
      })
    },
    filterNode(value, data) {
      if (!value) return true;
      return data[this.treeProps.label].indexOf(value) !== -1;
    },
    loadNode(node, resolve) {
      const nodeData = node.data
      const config = {
        treeInterfaceId: "",
        treeTemplateJson: []
      }
      if (config.treeInterfaceId) {
        //这里是为了拿到参数中关联的字段的值，后端自行拿
        if (config.treeTemplateJson && config.treeTemplateJson.length) {
          for (let i = 0; i < config.treeTemplateJson.length; i++) {
            const element = config.treeTemplateJson[i];
            element.defaultValue = nodeData[element.relationField] || ''
          }
        }
        //参数
        let query = {
          paramList: config.treeTemplateJson || [],
        }
        //接口
        getDataInterfaceRes(config.treeInterfaceId, query).then(res => {
          let data = res.data
          if (Array.isArray(data)) {
            resolve(data);
          } else {
            resolve([]);
          }
        })
      }
    },
    getColumnList() {
      // 没有开启权限
      this.columnOptions = this.transformColumnList(this.columnList)
    },
    transformColumnList(columnList) {
      let list = []
      for (let i = 0; i < columnList.length; i++) {
        const e = columnList[i];
        if (!e.prop.includes('-')) {
          list.push(e)
        } else {
          let prop = e.prop.split('-')[0]
          let label = e.label.split('-')[0]
          let vModel = e.prop.split('-')[1]
          let newItem = {
            align: "center",
            jnpfKey: "table",
            prop,
            label,
            children: []
          }
          e.vModel = vModel
          if (!this.expandObj.hasOwnProperty(`${prop}Expand`)) this.$set(this.expandObj, `${prop}Expand`, false)
          if (!list.some(o => o.prop === prop)) list.push(newItem)
          for (let i = 0; i < list.length; i++) {
            if (list[i].prop === prop) {
              list[i].children.push(e)
              break
            }
          }
        }
      }
      this.getMergeList(list)
      this.getExportList(list)
      return list
    },
    arraySpanMethod({ column }) {
      for (let i = 0; i < this.mergeList.length; i++) {
        if (column.property == this.mergeList[i].prop) {
          return [this.mergeList[i].rowspan, this.mergeList[i].colspan]
        }
      }
    },
    getMergeList(list) {
      let newList = JSON.parse(JSON.stringify(list))
      newList.forEach(item => {
        if (item.children && item.children.length) {
          let child = {
            prop: item.prop + '-child-first'
          }
          item.children.unshift(child)
        }
      })
      newList.forEach(item => {
        if (item.children && item.children.length) {
          item.children.forEach((child, index) => {
            if (index == 0) {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 1,
                colspan: item.children.length
              })
            } else {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 0,
                colspan: 0
              })
            }
          })
        } else {
          this.mergeList.push({
            prop: item.prop,
            rowspan: 1,
            colspan: 1
          })
        }
      })
    },
    getExportList(list) {
      let exportList = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].jnpfKey === 'table') {
          for (let j = 0; j < list[i].children.length; j++) {
            exportList.push(list[i].children[j])
          }
        } else {
          exportList.push(list[i])
        }
      }
      this.exportList = exportList
    },
    getindustryOptions() {
      getDictionaryDataSelector('523125631823643269').then(res => {
        this.industryOptions = res.data.list
        console.log(JSON.stringify(this.industryOptions))
      })
    },
    getregionOptions() {
      getDictionaryDataSelector('487278954734944325').then(res => {
        this.regionOptions = res.data.list
      })
    },
    goDetail(id) {
      let encodedId = btoa(id); // 编码  或者使用其他编码方式
      window.open(`/exampleDetail/${encodedId}`, '_blank');
      //记录点击量
      this.recordClickNum(id);
    },
    recordClickNum(id) {
      const url = `http://test-fzzxqy.demo-caii.com/cloud-api2/portal/exampleClickRecord?exampleId=${id}&user=${this.userInfo.userId}`;
      axios.get(url).then(res => {
        this.refresh(true)
      })
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
      this.listQuery.sidx = !order ? '' : prop
      this.initData()
    },
    async initSearchDataAndListData() {
      await this.initSearchData()
      this.initData()
    },
    //初始化查询的默认数据
    async initSearchData() {
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        keyword: this.keyword,
        dataType: 0,
        menuId: this.menuId,
        moduleId: '580023361787138501',
        type: 1,
      };
      request({
        url: `/api/example/Fz_learn_example/getList`,
        method: 'post',
        data: _query
      }).then(res => {
        var _list = res.data.list;
        this.list = _list.map(o => ({
          ...o,
          ...this.expandObj,
        }))
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        request({
          url: `/api/example/Fz_learn_example/${id}`,
          method: 'DELETE'
        }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            onClose: () => {
              this.initData()
            }
          });
        })
      }).catch(() => {
      });
    },
    handelUpload() {
      this.uploadBoxVisible = true
      this.$nextTick(() => {
        this.$refs.UploadBox.init("", "example/Fz_learn_example")
      })
    },
    openSuperQuery() {
      this.superQueryVisible = true
      this.$nextTick(() => {
        this.$refs.SuperQuery.init()
      })
    },
    superQuery(queryJson) {
      this.listQuery.superQueryJson = queryJson
      this.listQuery.currentPage = 1
      this.initData()
    },
    addOrUpdateHandle(row, isDetail) {
      let id = row ? row.id : ""
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.JNPFForm.init(id, isDetail, this.list)
      })
    },
    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.exportList)
      })
    },
    download(data) {
      let query = { ...data, ...this.listQuery, ...this.query, menuId: this.menuId }
      request({
        url: `/api/example/Fz_learn_example/Actions/Export`,
        method: 'post',
        data: query
      }).then(res => {
        if (!res.data.url) return
        this.jnpf.downloadFile(res.data.url)
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      })
    },
    search() {
      this.listQuery.currentPage = 1
      this.listQuery.pageSize = 20
      this.listQuery.sort = "desc"
      this.listQuery.sidx = "creatortime"
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      this.query = JSON.parse(JSON.stringify(this.queryData))
      this.search()
    },
    colseFlow(isrRefresh) {
      this.flowVisible = false
      if (isrRefresh) this.reset()
    },
  }
}
</script>
<style lang="scss" scoped>
#main {
  width: 100%;
  background: #ffffff;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 0.2fr 0.2fr auto 0.8fr;
  gap: 0px 0px;
  grid-template-areas:
    'head head head head'
    'nav nav nav nav'
    'example example example example'
    'friendship-link friendship-link friendship-link friendship-link'
    'footer footer footer footer';
}

.example {
  grid-area: example;
  background: #f5f7fa;
  .example-top {
    margin: 20px auto;
    width: 1200px;
    .market_request {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 0 0 22px 0;
      border-radius: 4px;
      padding: 25px 0;
      background: #ffffff;
      .market_request_left {
        display: flex;
        align-items: center;
      }
      ::v-deep .el-form-item {
        margin: 0;
        margin-right: 10px;
      }
    }

    .el-row {
      margin: 0px !important;
      background: #ffffff;
      border-radius: 5px;
      min-height: 80px;
      height: auto;
      width: 100%;

      ::v-deep .el-form-item__label {
        font-weight: bold;
      }
    }
  }

  .example-center {
    margin: 0px auto;
    width: 1200px;
    background-color: #f0f4f9;
    border-radius: 5px;
    ::v-deep .el-pagination__sizes {
      display: none;
    }

    ::v-deep .pagination-container {
      background-color: #f0f4f9;
    }

    .example-main {
      .example-list {
        display: flex;
        flex-direction: row;
        padding: 10px 20px;
        border-radius: 4px;
        background: #ffffff;
        text-decoration: none;
        cursor: pointer;
        margin-bottom: 20px;
        &:hover {
          transform: translateY(-5px);
          box-shadow: 0px 5px 8px 5px #3d3d3d50;
        }
        .example_level_box {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: space-between;
          width: 392px;
          height: 180px;
          border-radius: 8px;
          background: #1890ff10;
          border: 1px solid #1890ff60;
          overflow: auto;
          .box_tags {
            display: flex;
            justify-content: space-around;
            width: 100%;
            .tags {
              margin-top: 10px;
            }
          }
          .box_title {
            margin-top: 12px;
            font-weight: 500px;
            font-size: 18px;
          }
          .box_info {
            color: #ffffff;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 46px;
            background: #1890ff;
          }
        }
        .example-left {
          position: relative;
          display: flex;
          align-items: center;
          img {
            border-radius: 10px;
            width: 220px;
            height: 180px;
            max-height: 180px;
          }
          .image_shadow {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 27px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #ffffff;
            background: #3d3d3d30;
          }
        }

        .example-right {
          // width: calc(100% - 220px);
          flex: 1;
          display: flex;
          flex-direction: column;
          padding: 10px;
          border-right: 1px solid #3d3d3d30;
          margin-right: 20px;
          justify-content: space-between;
          cursor: pointer;
          .example-name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            color: #3d3d3d;
            font-size: 18px;
            font-weight: bold;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            height: 32px;
          }

          .example-com {
            font-size: 14px;
            color: #666666;
            line-height: 28px;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .example-service {
            font-size: 14px;
            color: #101010;
            line-height: 28px;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
          }

          .example-type {
            display: flex;
            flex-direction: row;

            label {
              width: 50%;
              font-size: 14px;
              color: #101010;
              line-height: 28px;
              cursor: pointer;
            }
          }

          .example-other {
            font-size: 14px;
            color: #101010;
            line-height: 25px;
          }
        }
      }
    }

    .cen-top {
      font-size: 32px;
      font-weight: 700;
      text-align: center;
      color: #000;
    }

    .tit_sec {
      font-weight: 400;
      text-align: center;
      font-size: 12px;
      color: #ccc;
      margin-bottom: 8px;
    }

    .tit_hr {
      width: 300px;
      height: 2px;
      margin: 10px auto;
      display: flex;

      .tit_red {
        width: 150px;
        height: 3px;
        background-color: #1890ff;
      }

      .tit_blue {
        width: 150px;
        height: 3px;
        background-color: #1890ff;
      }
    }

    .cen_con {
      font-size: 16px;
      font-weight: 400;
      margin-top: 30px;
      line-height: 28px;
      text-align: justify;
      text-indent: 2em;
    }

    .btn_list {
      height: 150px;
      margin-top: 50px;
      margin-bottom: 90px;
      display: flex;

      .btn_fir {
        width: 380px;
        height: 100%;
        margin: auto;
        border-radius: 30px;
        transform: translateY(-5px);
        box-shadow: 0px 4px 8px 5px rgba(0, 0, 0, 0.15);

        .link-i,
        i {
          width: 20%;
          font-size: 50px;
          font-weight: bold;
        }

        &:hover {
          transform: translateY(-15px);
          box-shadow: 0px 10px 8px 5px rgba(24, 144, 255, 0.5);
        }

        &:first-child {
          background: linear-gradient(to right, #034373, #1890ff);
        }

        &:last-child {
          background: linear-gradient(to right, #1890ff, #3eb8f1);
        }

        a {
          width: 100%;
          height: 100%;
          text-decoration: none;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
          color: #ffffff;
        }

        .link-text {
          font-size: 30px;
          font-family: 黑体;
          font-weight: bold;
        }
      }
    }
  }
}
.general_pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 10px 12px;
  .total {
    color: #00000099;
  }
  .pagination-container {
    margin: 0;
    padding: 0;
  }
}
.tags {
  // margin-left: 10px;
  .tag {
    padding: 2px 8px;
    font-size: 14px;
    border-radius: 3px;
    font-weight: 400;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .blue {
    color: #1890ff;
    background: #1890ff1a;
  }
  .gray {
    color: #3d3d3d;
    background: #3d3d3d1a;
  }
}
</style>
